import { Game } from "@sapi-game/main";
import { showWereWolfForm, WereWolfFormOptions } from "@/werewolf/func";
import { WereWolfModule } from "@/werewolf/module";
import { WereWolfVotePhase } from "@/werewolf/phases/vote";
import { WereWolfPlayer, WereWolfStatus } from "@/werewolf/player";

export class WereWolfVoteTool extends WereWolfModule.Component<
    unknown,
    WereWolfVotePhase
> {
    override onAttach(): void {
        this.reset();
        this.subscribe(
            Game.events.itemUse,
            (t) => {
                const p = t.source;
                const gamePlayer = this.context.players.getById(p.id);
                if (gamePlayer) {
                    this.showForm(gamePlayer);
                }
            },
            { itemId: "werewolf:vote", players: this.context.players }
        );
    }

    reset() {
        this.context.players.forEach((p) => {
            p.voted = false;
            p.votes = 0;
        });
    }

    voteFormOptions: WereWolfFormOptions = {
        title: "投票",
        body: "请选择你要投票的玩家",
        getPlayers: () =>
            this.context.players.filter((p) => p.status == WereWolfStatus.Live),
        buildPlayerName(player) {
            return `${player.name}(${player.votes}票)`;
        },
        onSelect: (player, selected) => {
            if (!this.isAttached) return;
            if (player.voted) {
                return player.sendMessage("你已经投过票了");
            }
            if (player.dead) {
                return player.sendMessage("你已经死亡，不能投票");
            }
            selected.votes++;
            player.voted = true;
            if (selected.player)
                this.state.voteDb.set(selected.player, selected.votes);
            this.context.players.sendMessage(
                `§e${player.name}§b§l将票投给了 §r§e${selected.name}`
            );
        },
    };

    showForm(p: WereWolfPlayer) {
        if (!p.player) return;
        showWereWolfForm(this.voteFormOptions, p);
    }
}
